/**
 * diff相关的工具方法
 */
import { parseDiff } from 'components/diffView';

const tools = {
  // 计算一共多少行增、多少行减
  getDiffsCount(diffs) {
    // 如果有等待点击加载的 diff，行数是算不对的，这时直接不展示行数
    let hasWaittingForClickDiff;

    const allChangesArr = diffs.map((item) => {
      if (item.diff === '$WAITING_FOR_CLICK_BIG_SIZE$') {
        hasWaittingForClickDiff = true;
      }
      const parsedDiff = parseDiff(item.diff);
      if (!parsedDiff[0]) {
        return [];
      }
      const { hunks } = parsedDiff[0];
      // const changes = hunks.map(hunk => hunk.changes);
      const changesArr = hunks.reduce((result, { changes }) => [...result, ...changes], []);
      return changesArr;
    });

    if (hasWaittingForClickDiff) {
      return null;
    }

    let allChanges = [];
    allChangesArr.forEach((item) => {
      allChanges = allChanges.concat(item);
    });

    let additions = 0;
    let deletions = 0;
    allChanges.forEach((change) => {
      if (change.type === 'insert') {
        additions += 1;
      } else if (change.type === 'delete') {
        deletions += 1;
      }
    });

    return {
      additions,
      deletions,
    };
  },
  getSingleDiffsCount(diff) {
    // 如果有等待点击加载的 diff，行数是算不对的，这时直接不展示行数
    let hasWaittingForClickDiff;

    if (diff.diff === '$WAITING_FOR_CLICK_BIG_SIZE$') {
      hasWaittingForClickDiff = true;
    }
    const parsedDiff = parseDiff(diff.diff);
    let changesArr;
    if (!parsedDiff[0]) {
      changesArr = [];
    } else {
      const { hunks } = parsedDiff[0];
      changesArr = hunks.reduce((result, { changes }) => [...result, ...changes], []);
    }

    if (hasWaittingForClickDiff) {
      return null;
    }

    let additions = 0;
    let deletions = 0;
    changesArr.forEach((change) => {
      if (change.type === 'insert') {
        additions += 1;
      } else if (change.type === 'delete') {
        deletions += 1;
      }
    });

    return {
      additions,
      deletions,
    };
  },
};

export default tools;
